package com.controller;

import com.service.IProductService;
import com.vo.productVo.ProductListRequestVo;
import com.vo.productVo.ProductListResponseVo;
import com.vo.productVo.addProductVo;
import com.vo.productVo.updateProductVo;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Describe 商品管理控制器
 */
@Controller
@RequestMapping("/product")
public class ProductController {
    @Resource
    IProductService productService;
    @Resource
    HttpServletRequest request;

    /**
     * 获取商品信息列表
     * @return
     */
    @RequestMapping("/getProductList")
    @ResponseBody
    public List<ProductListResponseVo> getProductList(ProductListRequestVo vo){
        Object session= request.getSession().getAttribute("user");
        if(session == null){
            System.out.println("没有session，无法进行操作");
        }
        if(session != null) {
            return productService.getProductList(vo);
        }
        return null;
    }


    /**
     * 修改商品信息
     */
    @PutMapping("/updateProduct")
    @ResponseBody
    public void updateProduct(@RequestBody updateProductVo vo){
        Object session= request.getSession().getAttribute("user");
        if(session == null){
            System.out.println("没有session，无法进行操作");
        }
        if(session != null) {
            productService.updateProduct(vo);
        }
    }

    /**
     * 上架已有商品
     */
    @DeleteMapping("/putAwayProduct")
    @ResponseBody
    public void putAwayProduct(Integer id){
        Object session= request.getSession().getAttribute("user");
        if(session == null){
            System.out.println("没有session，无法进行操作");
        }
        if(session != null) {
            productService.putAwayProduct(id);
        }
    }

    /**
     * 下架商品
     */
    @DeleteMapping("/soldOutProduct")
    @ResponseBody
    public void soldOutProduct(Integer id){
        Object session= request.getSession().getAttribute("user");
        if(session == null){
            System.out.println("没有session，无法进行操作");
        }
        if(session != null) {
            productService.soldOutProduct(id);
        }
    }


    /**
     * 上架新商品（添加记录）
     */
    @PostMapping("/addProduct")
    @ResponseBody
    public String addProduct(addProductVo addVo, MultipartFile file) throws IOException {
        String filename = UUID.randomUUID() + "_" + file.getOriginalFilename();
        File dirs = new File("src/main/resources/static/images/product/"+filename);
        if (file.isEmpty()){
            productService.addProduct(addVo);
            return "图片上传失败！";
        }else {
            file.transferTo(new File(dirs.getAbsolutePath()));
            addVo.setImage("/static/images/product/"+filename);
            productService.addProduct(addVo);
            return "添加成功!";
        }
    }


    /**
     * 下载商品信息
     */
    @GetMapping("/download")
    public void downloadExcel(HttpServletResponse response) throws IOException{
        List<ProductListResponseVo> vo = productService.getProductList(new ProductListRequestVo());
        ProductController productController = new ProductController();
        HSSFWorkbook wb = productController.downloadExcel(vo);
        OutputStream outputStream = response.getOutputStream();

        String fileName="商品信息表"+".xls";
        fileName= URLEncoder.encode(fileName,"UTF-8");
        response.setHeader("Content-disposition","attachment;filename"+fileName+";"+"filename*=utf-8''"+fileName);
        wb.write(outputStream);
        outputStream.close();
    }

    public HSSFWorkbook downloadExcel(List<ProductListResponseVo> vo){
        String [] excelHeader={"编号","名称","详情","库存","售价(元)","进价(元)","状态","销量","创建时间","更新时间"};
        HSSFWorkbook workbook=new HSSFWorkbook();
        HSSFSheet sheet=workbook.createSheet("商品表");
        HSSFRow row=sheet.createRow((int)0);
        HSSFCellStyle style=workbook.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //单元格式
        for(int i=0;i<excelHeader.length;i++){//设置列宽
            HSSFCell cell=row.createCell(i);
            cell.setCellValue(excelHeader[i]);
            cell.setCellStyle(style);
            sheet.autoSizeColumn(i);
            sheet.setColumnWidth(cell.getColumnIndex(),90*60);
        }
        for(int i=0;i<vo.size();i++){
            row=sheet.createRow(i+1);
            ProductListResponseVo products = vo.get(i);
            row.createCell(0).setCellValue(products.getId());
            row.createCell(1).setCellValue(products.getName());
            row.createCell(2).setCellValue(products.getDescribe());
            row.createCell(3).setCellValue(products.getStock());
            row.createCell(4).setCellValue(products.getSellingPrice());
            row.createCell(5).setCellValue(products.getPurchasingPrice());
            row.createCell(6).setCellValue(products.getStatus());
            row.createCell(7).setCellValue(products.getSales());
//            下载下面两个时间信息会报错
//            row.createCell(8).setCellValue(products.getCreateTime());
//            row.createCell(9).setCellValue(products.getUpdateTime());
        }
        return  workbook;
    }


}
